<?php
namespace Modules\Activity\Http\Controllers\Client\Leitai;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use \Modules\Activity\Entities\Leitai\Activity;

use Validator;
use ThrowException;
use DB;
use Auth;
use Cache;

class ActivityController extends Controller
{
    public function index(Request $req)
    {
        $min_id = 0;
        $options = $req->all();
        $options['per_page'] = 999999;
        $options['scopes'] = ['onStock'];
        $title = '';
        $options['where'] = [
            ['id', '>', 0]
        ];
        if ( isset( $options['title'] ) && $options['title'] ){
            $title = urldecode(trim($options['title']));
            $options['where'] = ['title'=>$title];
        }
        if ( isset( $options['play_type'] ) && $options['play_type'] ){
            $options['where'] = ['play_type'=>$options['play_type']];
        }

        $act = DB::table('leitai_activity')->where('title',$title)->first();
        $res = [];
        if ( isset($act->play_type) ){
            if ( $act->play_type == 4 || $act->play_type == 7 ) {
                $res = DB::select("SELECT COUNT(*) c FROM leitai_last_skus WHERE activity_id IN (SELECT id FROM leitai_activity WHERE title = '$title') AND last_prize_type = 3 AND stock = 0");
            }
        }else{
            $res = DB::select("select count(*) c from (select sum(b.stock) stocks from leitai_activity a left join leitai_skus b on a.id = b.activity_id where 
                a.title = '$title' group by activity_id having stocks =0 ) d ");
        }

        $max_index = isset($res[0]) ? $res[0]->c: 0;

        if ( isset( $options['min_id'] ) && $options['min_id'] ){
            $min_id = $options['min_id']-1;
        }else{
            $min_id = isset($res[0]) ? $res[0]->c: 0;
        }
        $options['only'] = [
            'id',
            'uuid',
            'money_price',
            'score_price',
            'title',
            'thumb',
            'play_type',
            'activity_type_text',
            'activity_type'
        ];
        $options['order_by'] = ['stock'=>'asc', 'id' => 'asc'];

        //$list = Activity::getList($options);
        $list = DB::table('leitai_activity')->where($options['where'])->orderBy('id', 'asc')->skip($min_id)->take(1)->get()->toArray();
        if(count($list) == 0){
            $list = DB::table('leitai_activity')->where($options['where'])->orderBy('stock', 'asc')->orderBy('id', 'asc')->take(1)->get()->toArray();
        }

        $list = object_to_array($list);
        if( isset($list[0]['play_type']) && $list[0]['play_type'] == 3 ){
            $list = DB::table('leitai_activity')->where($options['where'])->orderBy('id', 'asc')->skip($min_id)->take(1)->get()->toArray();
            if(count($list) == 0){
                $list = DB::table('leitai_activity')->where($options['where'])->orderBy('id', 'asc')->take(1)->get()->toArray();
            }
            $list = object_to_array($list);
        }
        //$totle = DB::select("select count(*) c from leitai_activity where title = '$title' ")->getOne();
        $totle = DB::table("leitai_activity")->where('title', $title)->first(array(
            \DB::raw('count(*) as totals')
        ));


        $rr = array();
        $rr['list'] = $list;
        $rr['item_total'] = $totle->totals;
        $rr['min_id'] = $min_id;
        $rr['max_index'] = $max_index;
        $rr['play_type'] = isset($list[0]['play_type']) ? $list[0]['play_type'] : 0;
        $rr['run_time'] = isset($list[0]['run_time']) ? $list[0]['run_time'] : 0;

        return $rr;;

    }

    public function show(Request $req, $uuid)
    {
        $cachedInfoKey = $uuid.time();
        $cache_ = Cache::get($cachedInfoKey);
        if ( !$cache_ ){
            Cache::put($cachedInfoKey, 'loading', 3);
            $item = Activity::getEntity([
                'uuid' => $uuid,
                'with' => ['skus', 'last_skus']
            ]);

            $only = [
                'id',
                'uuid',
                'title',
                'image_3d',
                'images',
                'money_price',
                'score_price',
                'sub_title',
                'union_status',
                'union_status_text',
                'is_invite_enabled',
                'is_share_enabled',
                'visit_total',
                'play_type',
                'open_value',
                'rules',
                'run_time',
                'skus' => [
                    '*' => [
                        'id',
                        'uuid',
                        'title',
                        'thumb',
                        'stock',
                        'sales',
                        'odds',
                        'money_price',
                        'list_weight',
                        'score_price'
                    ]
                ],
                'last_skus' => [
                    '*' => [
                        'id',
                        'uuid',
                        'title',
                        'thumb',
                        'stock',
                        'sales',
                        'money_price',
                        'list_weight',
                        'last_prize_type',
                        'score_price'
                    ]
                ]
            ];

            $info = $item->getInfo($only);
            $info['stock_has'] = 0;
            $info['stock_all'] = 0;
            if ( count($info) ){
                if ( isset($info['skus']) ){
                    $stock_all = array_sum(array_column($info['skus'], 'stock'));
                    $info['stock_has'] = $stock_all;

                    $sales_all = array_sum(array_column($info['skus'], 'sales'));
                    $info['stock_all'] = $stock_all+$sales_all;

                    if ( $info['play_type'] == 6 ){
                        $odds = $stock_all > 0 ? 1 / $stock_all * 100 : 0;
                        foreach ( $info['skus'] as $k => $v ){
                            $info['skus'][$k]['odds'] = $odds * $v['stock'];
                        }
                    }

                    $skus_arr = array_column($info['skus'], 'list_weight');
                    array_multisort($skus_arr, SORT_DESC, $info['skus']);
                }
                if ( $info['play_type'] == 4 || $info['play_type'] == 7 ){
                    $info['stock_all'] = $info['open_value'];
                    $stock_info = array_column($info['last_skus'], null, 'last_prize_type');
                    $info['stock_has'] = $stock_info[3]['stock'];
                    $info['skus'] = array_merge($info['skus'], $info['last_skus']);

                    $all_num = array_column($info['skus'],'list_weight');
                    array_multisort($all_num,SORT_DESC, $info['skus']);

                    unset($info['last_skus']);
                }
            }

            Cache::put($cachedInfoKey, json_encode($info), 3);
            return [
                'info' => $info,
                // 'lastInfo'=>$lastInfo,
            ];
        }else{
            if ( $cache_ != 'loading' ){
                return [
                    'info' => json_decode($cache_, true),
                ];
            }else{
                sleep(1);
                return self::getCacheShow($cachedInfoKey);
            }
        }
    }

    public function getCacheShow($cachedInfoKey, $i=0)
    {
        $cache_ = Cache::get($cachedInfoKey);
        if ( $cache_ && $cache_ != 'loading' ){
            return [
                'info' => json_decode($cache_, true),
            ];
        }else{
            sleep(1);
            $i++;
            if ( $i>= 10 ){
                return [
                    'info' => [],
                ];
            }
            return self::getCacheShow($cachedInfoKey, $i);
        }
    }

    public function getCacheIndex($cachedInfoKey, $i=0)
    {
        $cache_ = Cache::get($cachedInfoKey);
        if ( $cache_ && $cache_ != 'loading' ){
            return json_decode($cache_, true);
        }else{
            sleep(1);
            $i++;
            if ( $i>= 10 ){
                return [];
            }
            return self::getCacheShow($cachedInfoKey, $i);
        }
    }

    public function leitaiLog(Request $req, $id)
    {
        $options = $req->all();

        $limit = isset($options['limit']) && $options['limit'] > 0 ? $options['limit'] : 100;
        $offset = isset($options['offset']) && $options['offset'] > 0 ? $options['offset'] : 0;

        if ( $id ){
            $play_type = DB::select("select play_type from leitai_activity where id = $id ");
            if ( $play_type[0]->play_type == 4 || $play_type[0]->play_type == 7 ){
                $db = "package_assets a left join package_skus s on a.id = s.package_asset_id 
                    left join orders o on s.pay_order_id = o.id 
                    left join users u on s.user_id = u.id 
                    left join leitai_last_skus l on l.activity_id = $id and s.title = l.title and s.sku_id = l.id
                    left join leitai_skus ls on ls.activity_id = $id and s.title = ls.title and s.sku_id = ls.id
                    ";
                $field = "a.created_at, s.title, s.thumb sku_pic, total, u.name user_name, headimg
                    , if(l.last_prize_type = 3, 0, if(l.list_weight is not null, l.list_weight, ls.list_weight)) list_weight, l.last_prize_type";
                $res = DB::select("select $field from $db where pay_type is not null and a.node_type = 'leitai' and a.node_id = $id order by list_weight desc, s.id desc limit $limit offset $offset ");

                if ( count($res) == 0 ){
                    $res = DB::select("select a.created_at, `name` user_name, headimg from orders a left join users b on a.user_id = b.id where pay_type is not null and node_type = 'leitai' and node_id = $id order by a.id desc limit $limit offset $offset ");
                    if ( count($res) == 0 ){
                        echo '';
                        die;
                    }

                    $res = object_to_array($res);
                    return $res;
                }

                $res = object_to_array($res);

                foreach ( $res as $k => $v ){
                    $res[$k]['star'] = 0;
                    $level = mb_substr(trim($v['title']), 0, 2);
                    switch ($level){
                        case '隐藏' : $res[$k]['star'] = 1; break;
                        case '稀有' : $res[$k]['star'] = 2; break;
                        case '超神' : $res[$k]['star'] = 3; break;
                        case '欧皇' : $res[$k]['star'] = 4; break;
                    }

                    if ( mb_substr(trim($v['title']), 0, 1) == 'S' ) $res[$k]['star'] = 2;
                    if ( mb_substr(trim($v['title']), 0, 2) == 'SS' ) $res[$k]['star'] = 3;
                    if ( mb_substr(trim($v['title']), 0, 3) == 'SSS' ) $res[$k]['star'] = 4;
                    if ( mb_substr(trim($v['title']), 0, 2) == '空车' ) $res[$k]['star'] = 4;
                }

                $created_at = max(array_column($res, 'created_at'));
                foreach ( $res as &$v ){
                    if ( $v['last_prize_type'] != 3 ){
                        $v['created_at'] = $created_at;
                    }
                }


                return $res;
            }
        }

        $db = "package_assets a left join package_skus s on a.id = s.package_asset_id 
                    left join users u on s.user_id = u.id 
                    left join leitai_last_skus l on l.activity_id = $id and s.title = l.title 
                    left join leitai_skus ls on ls.activity_id = $id and s.title = ls.title 
                    ";
        $field = "a.created_at, s.title, s.thumb sku_pic, total, u.name user_name, headimg
                    , if(l.last_prize_type = 3, 0, if(l.list_weight is not null, l.list_weight, ls.list_weight)) list_weight, l.last_prize_type";
        $res = DB::select("select $field from $db where a.node_type = 'leitai' and a.node_id = $id order by last_prize_type desc, a.id desc limit $limit offset $offset ");

        if ( count($res) == 0 ){
            echo '';
            die;
        }

        $res = object_to_array($res);

        foreach ( $res as $k => $v ){
            $res[$k]['star'] = 0;
            $level = mb_substr(trim($v['title']), 0, 2);
            switch ($level){
                case '隐藏' : $res[$k]['star'] = 1; break;
                case '稀有' : $res[$k]['star'] = 2; break;
                case '超神' : $res[$k]['star'] = 3; break;
                case '欧皇' : $res[$k]['star'] = 4; break;
            }

            if ( mb_substr(trim($v['title']), 0, 1) == 'S' ) $res[$k]['star'] = 2;
            if ( mb_substr(trim($v['title']), 0, 2) == 'SS' ) $res[$k]['star'] = 3;
            if ( mb_substr(trim($v['title']), 0, 3) == 'SSS' ) $res[$k]['star'] = 4;
            if ( mb_substr(trim($v['title']), 0, 2) == '空车' ) $res[$k]['star'] = 4;
        }

        if ( $play_type[0]->play_type == 5 ){
            // 双人PK 除了基础将（保底奖）其他显示时间为开奖时间
            $created_at = max(array_column($res, 'created_at'));
            foreach ( $res as &$v ){
                if ( $v['last_prize_type'] > 0 ){
                    $v['created_at'] = $created_at;
                }
            }
        }

        return $res;
    }

    public function leitaisBang(Request $req, $id)
    {
        $activity = Activity::getEntity([
            'id' => $id
        ]);

        if ( in_array($activity['play_type'], [4,5]) ){
            $db = "package_assets a 
                    left join package_skus s on a.id = s.package_asset_id 
                    left join users u on s.user_id = u.id  ";
            $field = "u.name user_name, headimg, '1' totals";
            $res = DB::select("select $field from $db where a.node_type = 'leitai' and a.node_id = $id group by user_name, headimg order by totals desc ");
        }elseif ( in_array($activity['play_type'], [7]) ){
            $db = "package_assets a 
                    left join package_skus s on a.id = s.package_asset_id 
                    left join users u on s.user_id = u.id  ";
            $field = "u.name user_name, headimg, sum(sku_total) totals";
            $res = DB::select("select $field from $db where a.node_type = 'leitai' and a.node_id = $id group by user_name, headimg order by totals desc ");
        }else{
            $db = "package_assets a 
                    left join package_skus s on a.id = s.package_asset_id 
                    left join users u on s.user_id = u.id 
                    left join leitai_last_skus l on l.activity_id = $id and s.title = l.title ";
            $field = "u.name user_name, headimg, sum(if(l.id>0, 0, total)) totals";
            $res = DB::select("select $field from $db where a.node_type = 'leitai' and a.node_id = $id group by user_name, headimg having totals > 0 order by totals desc ");
        }

        if ( count($res) == 0 ){
            echo '';
            die;
        }

        $res = object_to_array($res);
        return $res;
    }


    public function getGroupList(Request $req)
    {
        $options = $req->all();
        $status = isset($options['status']) && $options['status'] == 'off_stock' ? 0 : 1;
        $w = '';

        $header_arr = explode('-', $req->header('Client-Type'));
        $platformType = @$header_arr[0];
        $clientType = @$header_arr[2];

        if ( $platformType == 'app' && $clientType == 'app' ){
//            $w .= " and title like 'APP_%' ";
        }else{
            $w .= " and title not like 'APP_%' ";
        }

        if ( isset($options['key']) && $options['key'] ){
            $w .= " and title like '%{$options['key']}%' ";
        }
        if ( isset($options['stock_no']) && $options['stock_no'] == 0 ){
            $w .= " and stock = 0 ";
        }
        if ( isset($options['stock_no']) && $options['stock_no'] == 1 ){
            $w .= " and stock > 0 ";
        }
        if ( isset($options['play_type']) && $options['play_type'] > 0 ){
            if ( $options['play_type'] == 3 ){
                $w .= " and play_type IN (3, 6) ";
            }else{
                $w .= " and play_type = ".$options['play_type'];
            }
        }else{
            $w .= " and play_type not in (3, 6) ";
        }

        $res = DB::select("select * from leitai_data_sum where status = $status $w order by list_weight desc, created_at desc ");

        if ( count($res) == 0 ){
            $res = [];
            return $res;
        }

        foreach ( $res as $k => $v ){
            $c = DB::select("select count(*) c from (select sum(b.stock) stocks from leitai_activity a left join leitai_skus b on a.id = b.activity_id where 
                a.title = '{$v->title}' group by activity_id having stocks =0 ) d ");
            $res[$k]->now_id = ($c[0]->c)+1;
            $res[$k]->title_app = ltrim($res[$k]->title, 'APP_');
        }

        return $res;
    }

    public function getLeitaiSku(Request $req, $activity_id)
    {
        $info = array();
        if ( $req->type == 1 ){
            $res_1 = DB::select("select * from leitai_last_skus where activity_id = $activity_id and last_prize_type = 5 order by list_weight desc ");
            $res_2 = DB::select("select * from leitai_skus where activity_id = $activity_id order by list_weight desc ");

            $res_1 = object_to_array($res_1);
            $res_2 = object_to_array($res_2);
            $info['skus'] = $res_2;
            $info['last_skus'] = $res_1;
        }

        if ( $req->type == 2 ){
            $res = DB::select("select * from leitai_last_skus where activity_id = $activity_id and last_prize_type = 6 order by list_weight desc ");
            $res = object_to_array($res);
            $info['skus'] = $res;
        }

        if ( $req->type == 3 ){
            $res = DB::select("select * from leitai_last_skus where activity_id = $activity_id and last_prize_type = 7 order by list_weight desc ");
            $res = object_to_array($res);
            $info['skus'] = $res;
        }

        $order_s = DB::table('leitai_skus')->where('activity_id', $activity_id)->first(array(
            \DB::raw('sum(stock) as stock'),
            \DB::raw('sum(sales) as sales')
        ));
        $info['stock_all'] = $order_s->stock + $order_s->sales;
        $info['stock_has'] = $order_s->stock;
        $more = DB::table('leitai_activity')->where('id', $activity_id)->first();
        $info['rules'] = $more->rules;
        $info['title'] = $more->title;
        $info['run_time'] = $more->run_time;
        $info['id'] = $activity_id;

        return['info'=>$info];
    }

    public function getKongCheNums(Request $req)
    {
        $rule = [
            'activity_title'
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        $options = $req->all();
        $title = urldecode(trim($options['activity_title']));

        $res = DB::table('kongche')->where('user_id', $user->id)->where('activity_title', $title)->first();
        $res = object_to_array($res);

        $nums = isset($res['nums']) ? $res['nums'] : 0;
        return $nums;
    }

}
